<template>
    <div class="logobjBox">
        <div class="cardBox">
            <img class="cardBoxImg" src="/src/assets/logobj.png" alt="">
            <div v-if="logoType == '登录'" class="cardBoxRight">
                <div class="cardBoxTitle">账号登录</div>
                <div class="cardBoxForm">
                    <el-form :model="loginForm" label-width="auto" label-position="top" ref="loginRef"
                        :rules="loginRules">
                        <el-form-item label="账号" prop="Account">
                            <el-input v-model="loginForm.Account" type="text" size="large" autocomplete="username"
                                placeholder="账号">
                            </el-input>
                        </el-form-item>
                        <el-form-item label="密码" prop="Password">
                            <el-input v-model="loginForm.Password" type="password" size="large" autocomplete="current-password"
                                placeholder="密码" @keyup.enter="handleLogin">
                            </el-input>
                        </el-form-item>
                        <el-form-item label="验证码" prop="openauth">
                            <el-input v-model="loginForm.openauth" size="large" auto-complete="off" placeholder="验证码"
                                style="width: 63%" @keyup.enter="handleLogin">
                            </el-input>
                            <div class="login-code">
                                <identify v-model="codeUrl" ref="identifyRef" ></identify>
                            </div>
                        </el-form-item>
                    </el-form>
                </div>
                <div class="bottomBox">
                    <div class="buttonBox" @click.prevent="handleLogin">
                        <span v-if="!loading">登 录</span>
                        <span v-else>登 录 中...</span>
                    </div>
                    <div class="buttonText" >
                        <span class="fhsyBox" @click="fhsyFun()">返回首页</span>
                    </div>
                    <div v-if="false" class="buttonText">
                        <span>还没有账号？</span>
                        <span class="buttonTextlv" @click="ljzcTypefun('注册')">立即注册</span>
                    </div>
                </div>
            </div>
            <div v-if="logoType == '注册'" class="cardBoxRight">
                <div class="cardBoxTitle">账号注册</div>
                <div class="cardBoxForm">
                    <el-form :model="registerForm" label-width="auto" label-position="top" ref="registerRef"
                        :rules="registerRules">
                        <el-form-item label="账号" prop="Account">
                            <el-input v-model="registerForm.Account" type="text" size="large" auto-complete="off"
                                placeholder="账号">
                            </el-input>
                        </el-form-item>
                        <el-form-item label="密码" prop="Password">
                            <el-input v-model="registerForm.Password" type="password" size="large" auto-complete="off"
                                placeholder="密码" @keyup.enter="handleRegister">
                            </el-input>
                        </el-form-item>
                        <el-form-item label="确认密码" prop="confirmPassword">
                            <el-input v-model="registerForm.confirmPassword" type="password" size="large"
                                auto-complete="off" placeholder="确认密码" @keyup.enter="handleRegister">
                            </el-input>
                        </el-form-item>
                        <el-form-item label="验证码" prop="openauth">
                            <el-input v-model="registerForm.openauth" size="large" auto-complete="off" placeholder="验证码"
                                style="width: 63%" @keyup.enter="handleRegister">
                            </el-input>
                            <div class="login-code">
                                <!-- <img :src="codeUrl" @click="getCode" class="login-code-img" /> -->
                            </div>
                        </el-form-item>
                    </el-form>
                </div>
                <div class="bottomBox">
                    <div class="buttonBox" @click.prevent="handleRegister">
                        <span v-if="!loading">注 册</span>
                        <span v-else>注 册 中...</span>
                    </div>
                    <div class="buttonText">
                        <span>已有账号？</span>
                        <span class="buttonTextlv" @click="ljzcTypefun('登录')">返回登录</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script setup>
import identify from '@/components/general/VerificationCode.vue';
import { login, register } from "@/api/api.js";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import { ref, onMounted } from 'vue';
import { ElForm, ElMessage, ElMessageBox } from 'element-plus';
import { setToken } from '@/utils/auth'
import { useRoute, useRouter } from 'vue-router';
const route = useRoute();
const router = useRouter();
import { useStore } from '@/store/store';
const store = useStore()

const logoType = ref('登录')
onMounted(() => {
    if (route.query.logoType) {
        logoType.value = route.query.logoType;
    }
    getCode(); // 页面加载时获取验证码
});
const ljzcTypefun = (type) => {
    logoType.value = type
    loginForm.value = {
        Account: "",
        Password: "",
        openauth: "",
    }
    registerForm.value = {
        Account: "",
        Password: "",
        confirmPassword: "",
        openauth: "",
    }
    getCode()
}
const loginForm = ref({
    Account: "",
    Password: "",
    openauth: "",
});
const codeUrl = ref('');
const verifyCaptcha = (rule, value, callback) => {
    if (!value) {
        callback(new Error('验证码不能为空'))
    } else if (value.toLowerCase() !== codeUrl.value.toLowerCase()) {
        callback(new Error('验证码不正确'))
    } else {
        callback()
    }
}

const loginRules = {
    Account: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
    Password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
    openauth: [{ required: true, trigger: "change", message: "请输入验证码" },
    { validator: verifyCaptcha, trigger: "blur" }
    ]
};
const registerForm = ref({
    Account: "",
    Password: "",
    confirmPassword: "",
    openauth: "",
});
const equalToPassword = (rule, value, callback) => {
    if (registerForm.value.Password !== value) {
        callback(new Error("两次输入的密码不一致"));
    } else {
        callback();
    }
};
const registerRules = {
    Account: [
        { required: true, trigger: "blur", message: "请输入您的账号" },
        { min: 2, max: 20, message: "用户账号长度必须介于 2 和 20 之间", trigger: "blur" }
    ],
    Password: [
        { required: true, trigger: "blur", message: "请输入您的密码" },
        { min: 5, max: 20, message: "用户密码长度必须介于 5 和 20 之间", trigger: "blur" },
        { pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\\ |", trigger: "blur" }
    ],
    confirmPassword: [
        { required: true, trigger: "blur", message: "请再次输入您的密码" },
        { required: true, validator: equalToPassword, trigger: "blur" }
    ],
    openauth: [{ required: true, trigger: "change", message: "请输入验证码" }]
};
const loading = ref(false);

const loginRef = ref();
const handleLogin = async () => {
    if (!loginRef.value) return;
    await loginRef.value.validate(async (valid) => {
        if (valid) {
            loading.value = true;
            const encryptedPassword = await encrypt(loginForm.value.Password)
            const logoParameter = {
                Account: loginForm.value.Account,
                Password: encryptedPassword,
                openauth: loginForm.value.openauth,
            }
            const logoData = await login(logoParameter)
            if (logoData.code === 200) {
                setToken(logoData.token)
                store.token = logoData.token
                loading.value = false;
                if (await store.getInfo()) {
                    ElMessage.success('登录成功')
                    router.push('/')
                }
            }
            else {
                loading.value = false;
                ElMessage.error(logoData.msg || '登录失败，请重试')
                getCode()
            }
        }
    });
}
const registerRef = ref();
const handleRegister = async () => {
    if (!registerRef.value) return;
    await registerRef.value.validate(async (valid) => {
        if (valid) {
            loading.value = true;
            const res = await register(registerForm.value)
            loading.value = false;
            if (res.code === 200) {
                ElMessageBox.alert(`<font color='#2b893a'>恭喜你，您的账号${registerForm.value.Account}注册成功！请进行登录。</font>`, "系统提示", {
                    dangerouslyUseHTMLString: true,
                    type: "success",
                }).then(() => {
                    logoType.value = '登录'
                    loginForm.value.Account = registerForm.value.Account
                    loginForm.value.Password = registerForm.value.Password
                    getCode()
                }).catch(() => {
                    registerForm.value = {
                        Account: "",
                        Password: "",
                        confirmPassword: "",
                        openauth: "",
                    }
                });
            }
            else {
                ElMessage.error(res.msg || '注册失败，请重试')
                getCode()
            }
        }
    })
}
// 刷新验证码
const identifyRef = ref(null)
function getCode() {
    identifyRef.value?.changeCode()
}

</script>
<style scoped lang="scss">
.logobjBox {
    background: #f4f9ff;
    width: 100vw;
    height: 100vh;
    position: relative;

    .cardBox {
        width: 60%;
        height: 80%;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: #ffffff;
        border-radius: 21px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1), 0 8px 16px rgba(0, 0, 0, 0.1);
        display: flex;
        overflow: hidden;

        .cardBoxImg {
            width: 50%;
            height: 100%; // 继承父级高度
            object-fit: cover; // 保持图片比例
        }

        .cardBoxRight {
            width: 50%;
            padding: 40px 0;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: space-around;

            .cardBoxTitle {
                font-size: 36px;
                font-weight: bold;
                margin-top: 40px;
            }

            .cardBoxForm {
                width: 70%;
                margin-top: 20px;

                .el-form-item {
                    margin-bottom: 28px;

                    :deep(.el-input__inner) {
                        height: 50px;
                        line-height: 50px;
                        border-radius: 8px;
                    }
                }

                .login-code {
                    width: 36%;
                    height: 50px;
                    float: right;
                }
            }

            .bottomBox {
                margin-top: 40px;

                .buttonBox {
                    background: $button-color;
                    border-radius: 24px;
                    font-size: 16px;
                    color: #FFFFFF;
                    padding: 14px 170px;
                    cursor: pointer;
                }

                .buttonText {
                    margin-top: 20px;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    font-size: 16px;
                    .fhsyBox {
                        cursor: pointer;
                        font-size: 14px;
                        &:hover {
                            color: $button-color;
                        }
                    }

                    .buttonTextlv {
                        color: $button-color;
                        cursor: pointer;
                    }
                }
            }
        }
    }
}
</style>